from dao import Dao
from model.category import Category
from bson.dbref import DBRef

class CategoryDao(Dao):
    def __init__(self):
        Dao.__init__(self, Category)
        self.collection = 'categories'

    def insert(self, category):
        """Save the user object to collection
        Arguments:
            user --- The User Model object
        """
        if isinstance(category, Category):
            # Insert except ID field, because ID will be automatically generated
            _dict = {}
            _dict['name'] = category.name
            _dict['description'] = category.description
            
            if isinstance(category.parent, Category):
                _dict['parent'] = DBRef('categories', category.parent._id)
            else:
                _dict['parent'] = None # For root
                
            return self.db.insert(self.collection, _dict)
        return None
    
    def save(self, model):
        """Updates an existing document or inserts a new document, depending on its document parameter.
        Arguments:
            model --- The Model object with id,  if model is a dict type, the dbref field must be DBRef type
        Return:
            The '_id' value of to_save or [None] if manipulate is False and to_save has no _id field.
        """
        # The ID field must exist
        if isinstance(model, dict):
            return self.db.save(self.collection, model)
        else:
            _dict = model.__dict__
            if isinstance(model.parent, Category):
                _dict['parent'] = DBRef('categories', model.parent._id)
            else:
                _dict['parent'] = None # For root
            return self.db.save(self.collection, _dict)